﻿using SqlSugar;

namespace GMS.NET.SqlSugarCore.DbCore
{
    public static class DbTools
    {
        /// <summary>
        /// 获取分表的取表范围
        /// </summary>
        /// <param name="spInfos"></param>
        /// <returns></returns>
        public static IEnumerable<SplitTableInfo> GetRange(this List<SplitTableInfo> spInfos)
        {
            return spInfos.Take(DateTime.Now.Month <= 3 ? 2 : 1);
        }
        /// <summary>
        /// 批量赋值Guid
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataSet"></param>
        /// <returns></returns>
        public static List<T> SetGuid<T>(this List<T> dataSet)
        {
            var Ids = GetGuidList(dataSet.Count());
            Parallel.For(0, dataSet.Count, i =>
            {
                var item = dataSet[i];
                var idProperty = item!.GetType().GetProperty("Id");
                if (idProperty != null && idProperty.PropertyType == typeof(Guid))
                {
                    var idValue = Ids[i];
                    idProperty.SetValue(item, idValue);
                }
            });
            return dataSet;
        }
        /// <summary>
        /// 批量生成的不重复的Guid
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private static List<Guid> GetGuidList(int count)
        {
            HashSet<Guid> generatedGuids = new HashSet<Guid>();

            while (generatedGuids.Count < count)
            {
                Guid newGuid = Guid.NewGuid();

                if (!generatedGuids.Contains(newGuid))
                {
                    generatedGuids.Add(newGuid);
                }
            }
            return generatedGuids.ToList();
        }
    }
}
